<!--
@author: hbr
@create: 2022-05-06 14:05:06
@desc:
@update: 2022-05-06 14:05:06
@file:
-->
<script setup>
import dayjs from 'dayjs'
import SQuery from '@/views/workOrder/components/SQuery.vue'
import { setTitle } from '@/utils/setTitle'
import { useRoute } from 'vue-router/composables'
import { getDisposeOrderList } from '@/apis/order.js'
import NoData from '@/components/NoData.vue'
import { usePermissionStore } from '@/stores/permission.js'
import { getStartEndTime } from '@/utils/date.js'
import MQuery from '@/views/workOrder/components/MQuery.vue'
import OrderItem from '@/views/workOrder/components/OrderItem.vue'
import DisposeUnit from '@/views/workOrder/components/DisposeUnit.vue'
import MoreSelect from '@/views/workOrder/components/MoreSelect.vue'
import OrderStatusSelect from '@/views/workOrder/components/OrderStatusSelect.vue'
import AreaSelect from '@/views/workOrder/components/AreaSelect.vue'
import { setCustomTitle } from '@/utils/unit.js'
import { useCommonTypesStore } from '@/stores/commonTypes.js'
const { user } = usePermissionStore()
const { state: commonState } = useCommonTypesStore()
// 弹框是否显示
const isShowTimePopup = ref(false)
const isShowAreaPopup = ref(false)
const isShowMorePopup = ref(false)
const isShowStatusPopup = ref(false)
const isShowUnitPopup = ref(false)
const isKeywordSearch = ref(false)

// 对应标题显示
const areaTitle = ref('')
const timeTitle = ref('')
const statusTitle = ref('')
const unitTitle = ref('')
const moreTitle = ref('')

// 路由
const route = useRoute()
const queryObject = ref(route.query)

const state = reactive({
  selectOrderType: [], // 舆情类型选择列表
  selectOrderLevel: [], // 舆情级别选择列表
  selectOrderTimeout: [], // 舆情超时选择列表
  selectOrderStatus: [], // 处理状态选择列表
  selectOrderArea: [], // 区域选择列表
  officeList: [], // 选择的所属处室
  directUnitList: [], // 选择的直属单位
  timeDefaultData: [
    new Date(getStartEndTime(-30, 0).startTime),
    new Date(getStartEndTime(-30, 0).endTime)
  ],
  tableData: [],
  loading: false,
  refreshLoading: false,
  Sloading: false,
  finished: false,
  queryField: {
    keyword: null,
    statusList: null, // 处置状态 "FINISHED"已完成,
    infoTypeList: null, // 工单类型
    infoLevelList: null, // 舆情级别
    areaCodeList: null, // 所属州市 州市代码
    officeIdList: null, // 所属处室 id
    directUnitIdList: [], // 直属单位 id
    superviseStatusList: null, // 督办反馈状态 0未督办, 1已督办, 2未反馈, 3已反馈
    timeoutStatusList: null, // 办理状态 0正常, 1即将超时, 2已超时
    createTimeStart: '', // 开始时间 2024-10-09 00:00:00
    createTimeEnd: '', // 结束时间 2024-11-08 23:59:59
    page: {
      current: 1,
      size: 10
    }
  }
})

// 初始化数据-下拉刷新、搜索、
const initData = async () => {
  state.queryField.page.current = 1
  state.finished = false
  try {
    await getDisposeOrder('refresh')
  } catch (e) {
    console.log(e)
  }
  state.refreshLoading = false
}

const clearFrom = () => {
  state.queryField.statusList = null
  state.queryField.infoLevelList = null
  state.queryField.infoTypeList = null
  state.queryField.timeoutStatusList = null
  state.queryField.areaCodeList = null
  state.queryField.directUnitIdList = null
}

// 搜索查询功能
const searchChang = async () => {
  isKeywordSearch.value = !!state.queryField.keyword
  state.queryField.page.current = 1
  clearFrom()
  await initData()
}

// 获取接口数据
const getDisposeOrder = async (type) => {
  if (state.Sloading) return
  state.Sloading = true
  await getDisposeOrderList(state.queryField)
    .then((res) => {
      if (res.errorcode == 0) {
        const datas = res.data.records.map((item) => {
          return item
        })
        if (type === 'refresh') {
          state.tableData = []
          state.tableData = datas || []
        } else {
          state.tableData.push(...datas)
        }
        state.queryField.page.current++
        const pageNum = parseInt(res.data.pages)
        if (state.queryField.page.current > pageNum) {
          state.finished = true
        }
        state.loading = false
        state.Sloading = false
      } else {
        state.finished = true
        state.loading = false
        state.Sloading = false
      }
    })
    .catch((error) => {
      console.error('请求失败:', error)
      state.loading = false
      state.Sloading = false
    })
}

// 处理状态查询确定
const statusChange = () => {
  if (state.selectOrderStatus.length) {
    let text = state.selectOrderStatus.map((item) => item.label).join(',')
    statusTitle.value = setCustomTitle(text, 4)
    state.queryField.statusList = state.selectOrderStatus.map(
      (item) => item.value
    )
  } else {
    state.queryField.statusList = []
    statusTitle.value = ''
  }
  initData()
  isShowStatusPopup.value = false
}

// 更多筛选功能查询确定
const moreQueryChange = () => {
  if (
    state.selectOrderType.length ||
    state.selectOrderLevel.length ||
    state.selectOrderTimeout.length
  ) {
    state.queryField.infoTypeList = state.selectOrderType.map(
      (item) => item.dictValue
    )
    state.queryField.infoLevelList = state.selectOrderLevel.map(
      (item) => item.value
    )
    state.queryField.timeoutStatusList = state.selectOrderTimeout.map(
      (item) => item.value
    )
    let total =
      state.queryField.infoTypeList.length +
      state.queryField.infoLevelList.length +
      state.queryField.timeoutStatusList.length
    moreTitle.value = `更多筛选(${total})`
  } else {
    state.queryField.infoTypeList = []
    state.queryField.infoLevelList = []
    state.queryField.timeoutStatusList = []
    moreTitle.value = ''
  }
  isShowMorePopup.value = false
  initData()
}

// 投诉归属地查询确定
const areaChange = () => {
  if (state.selectOrderArea.length) {
    state.queryField.areaCodeList = state.selectOrderArea.map(
      (item) => item.areaCode
    )
    let text = state.selectOrderArea.map((item) => item.name).join(',')
    areaTitle.value = setCustomTitle(text, 17)
  } else {
    state.queryField.areaCodeList = []
    areaTitle.value = ''
  }
  isShowAreaPopup.value = false
  initData()
}

// 查询时间格式化
function formatDate(date) {
  return dayjs(date).format('YYYY-MM-DD')
}

// 时间区间查询
const onConfirm = async (date) => {
  const [start, end] = date
  isShowTimePopup.value = false
  timeTitle.value = setCustomTitle(formatDate(end), 10)
  state.queryField.createTimeStart = formatDate(start) + ' 00:00:00'
  state.queryField.createTimeEnd = formatDate(end) + ' 23:59:59'
  state.timeDefaultData = [
    new Date(state.queryField.createTimeStart),
    new Date(state.queryField.createTimeEnd)
  ]
  await initData()
}

// 处理单位选择
const disposeUnitSearch = () => {
  let text =
    state.officeList.map((item) => item.name).join(',') +
    state.directUnitList.map((item) => item.name).join(',')
  state.queryField.officeIdList = state.officeList.map((item) => item.id)
  state.queryField.directUnitIdList = state.directUnitList.map(
    (item) => item.id
  )
  if (text.length > 0) {
    unitTitle.value = setCustomTitle(text, 3)
  } else {
    unitTitle.value = ''
  }
  initData()
}

// 获取到url参数，进行赋值查询
const queryObjectFun = () => {
  const fields = [
    'nodeStatus',
    'superviseStatusList',
    'statusList',
    'infoLevelList',
    'timeoutStatusList'
  ]

  try {
    fields.forEach((field) => {
      if (
        queryObject.value[field] !== null &&
        queryObject.value[field] !== undefined
      ) {
        if (field === 'nodeStatus') {
          state.queryField[field] = queryObject.value[field]
        } else {
          handleEchoOptions(field)
        }
      }
    })
  } catch (error) {
    console.error('Error in queryObjectFun:', error)
  }
}
// 在进入页面的时候回显对应选项的状态
const handleEchoOptions = (option) => {
  switch (option) {
    case 'statusList':
      state.selectOrderStatus = commonState.workerOrderStatus.filter(
        (item) => item.value === queryObject.value[option]
      )
      statusChange()
      break
    case 'infoLevelList':
      state.selectOrderLevel = commonState.infoLevel.filter(
        (item) => item.value === Number(queryObject.value[option])
      )
      moreQueryChange()
      break
    case 'timeoutStatusList':
      state.selectOrderTimeout = commonState.timeoutData.filter(
        (item) => item.value === Number(queryObject.value[option])
      )
      moreQueryChange()
      break
    default:
      break
  }
}

onMounted(async () => {
  if (queryObject.value.title) {
    setTitle(queryObject.value.title)
  }
  areaTitle.value = user.areaName
  queryObjectFun()
  await initData()
})
</script>

<template>
  <section class="h-full w-full p-0 bg-#F8F9FC overflow-x-hidden">
    <!-- 搜索查询 -->
    <MQuery
      :model-value.sync="state.queryField.keyword"
      @search="searchChang"
    />
    <!--筛选条件-->
    <template v-if="!isKeywordSearch">
      <div class="flex items-center m-0 w-full px-12px py-10px">
        <SQuery
          v-if="user.level && Number(user.level || 0) <= 2"
          :show.sync="isShowAreaPopup"
          :title="areaTitle === '' ? '云南省' : areaTitle"
        />
      </div>
      <div
        class="text-#71747a text-14px flex items-center justify-start m-0 px-12px"
      >
        <SQuery
          :show.sync="isShowTimePopup"
          :title="timeTitle === '' ? '发起时间范围' : timeTitle"
          :active="timeTitle !== ''"
        />
        <SQuery
          :show.sync="isShowStatusPopup"
          :title="statusTitle === '' ? '办理状态' : statusTitle"
          :active="statusTitle !== ''"
        />
        <SQuery
          v-if="user.level && Number(user.level || 0) <= 2"
          :show.sync="isShowUnitPopup"
          :title="unitTitle === '' ? '处理单位' : unitTitle"
          :active="unitTitle !== ''"
        />
        <SQuery
          :show.sync="isShowMorePopup"
          :title="moreTitle === '' ? '更多筛选' : moreTitle"
          :active="moreTitle !== ''"
        />
      </div>
    </template>
    <!--总条数-->
    <template v-if="isKeywordSearch">
      <div class="px-12px pt-16px pb-5px">
        <p class="m-0 text-14px font-400 leading-20px text-#54565C">
          找到
          <span class="text-#1E2226 font-600">{{
            state.tableData.length
          }}</span>
          条数据
        </p>
      </div>
    </template>

    <NoData :white="false" v-if="state.tableData.length === 0" />
    <van-pull-refresh v-model="state.refreshLoading" @refresh="initData">
      <van-list
        v-model="state.loading"
        :finished="state.finished"
        :finished-text="state.tableData.length ? '没有更多了' : ''"
        @load="getDisposeOrder"
        :immediate-check="false"
        class="px-12px"
      >
        <OrderItem
          :key="item.id"
          v-for="item in state.tableData"
          :item="item"
        />
      </van-list>
    </van-pull-refresh>
    <!-- 发起时间范围 -->
    <van-calendar
      title="发起时间范围"
      v-model="isShowTimePopup"
      type="range"
      class="calendar-box"
      color="#36B374"
      :default-date="state.timeDefaultData"
      :min-date="new Date(getStartEndTime(-(365 * 10), 0).startTime)"
      :max-date="new Date(getStartEndTime(-(365 * 10), 0).endTime)"
      @confirm="onConfirm"
    />
    <!-- 归属地选择 -->
    <AreaSelect
      :show.sync="isShowAreaPopup"
      :area.sync="state.selectOrderArea"
      @confirm="areaChange"
      @reset="areaChange"
    />
    <!-- 处理单位 -->
    <DisposeUnit
      :show.sync="isShowUnitPopup"
      :office.sync="state.officeList"
      :direct-unit.sync="state.directUnitList"
      @search="disposeUnitSearch"
    />
    <!-- 处理状态 -->
    <OrderStatusSelect
      :show.sync="isShowStatusPopup"
      :order-status.sync="state.selectOrderStatus"
      @confirm="statusChange"
      @reset="statusChange"
    />
    <!-- 更多筛选 -->
    <MoreSelect
      :show.sync="isShowMorePopup"
      :info-type.sync="state.selectOrderType"
      :info-level.sync="state.selectOrderLevel"
      :timeout.sync="state.selectOrderTimeout"
      @confirm="moreQueryChange"
      @reset="moreQueryChange"
    />
  </section>
</template>

<style scoped lang="less">
:deep(.calendar-box) {
  .van-icon-cross::before {
    content: '\e65e';
  }
}
</style>
